Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
Make the loop run after "return" statement. [React JS]

Aim: I want to render 64 <Square /> elements with <br/> after each 8 elements

Problem: The script outputs just one block and then stops and nothing more happens.

Source Code:

import React from 'react';
import ReactDOM from 'react-dom';
import './style.css';

class Square extends React.Component {
  render() {
    return <div id="block"></div>;
  }
}

class Board extends React.Component {
  renderSquare() {
    for (let i = 1; i <= 64; i++) {
      if (i % 8 == 0) {
        return <br />;
      } else {
        return <Square />;
      }
    }
  }
  render() {
    return <div>{this.renderSquare()}</div>;
  }
}

function Game() {
  return (
    <div id="board">
      <Board />
    </div>
  );
}

ReactDOM.render(<Game />, document.getElementById('root'));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Using return statement will exit the function after first match, hence in first loop it exits and only displays 1st element, you need to use an array, store the elements in it, and then return the array.

Change your renderSquare method to following

renderSquare() {
    const items = [];
    for (let i = 1; i <= 64; i++) {
        if (i % 8 === 0) {
            items.push(<br />);
        } else {
            items.push(<Square />);
        }
    }
    return items;
}

Update

if you want to print 64 times then use the following

renderSquare() {
    const items = [];
    for (let i = 1; i <= 64; i++) {
        items.push(<Square />);
        if (i % 8 === 0) {
            items.push(<br />);
        }
    }
    return items;
}

Check this https://codesandbox.io/s/peaceful-brattain-pj32le?file=/src/App.js

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda